﻿using DFGK_WMS.Model.DTO;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;

namespace DFGK_WMS.Model.Helper
{
    public class HttpHelper
    {
        private static readonly HttpClient _httpClient = new HttpClient();

        private static readonly string baseUrl = "http://example.com"; // 请替换为实际的baseUrl

        public static async Task<string> SendGetRequest(string url, Dictionary<string, string> queryParams = null)
        {
            try
            {
                if (queryParams != null)
                {
                    var queryString = new FormUrlEncodedContent(queryParams);
                    url += $"?{queryString.ReadAsStringAsync().Result}";
                }

                HttpResponseMessage response = await _httpClient.GetAsync(url);
                response.EnsureSuccessStatusCode();

                return await response.Content.ReadAsStringAsync();
            }
            catch (Exception ex)
            {
                // 处理异常，例如记录日志或抛出自定义异常
                Console.WriteLine($"An error occurred: {ex.Message}");
                throw;
            }
        }

        public static async Task<string> SendPostRequest(string url, string requestBody, Dictionary<string, string> queryParams = null)
        {
            try
            {
                if (queryParams != null)
                {
                    var queryString = new FormUrlEncodedContent(queryParams);
                    url += $"?{queryString.ReadAsStringAsync().Result}";
                }

                HttpContent content = new StringContent(requestBody);
                HttpResponseMessage response = await _httpClient.PostAsync(url, content);
                response.EnsureSuccessStatusCode();

                return await response.Content.ReadAsStringAsync();
            }
            catch (Exception ex)
            {
                // 处理异常
                Console.WriteLine($"An error occurred: {ex.Message}");
                throw;
            }
        }

        /// <summary>
        /// 获取token
        /// </summary>
        /// <returns></returns>
        public static async Task<string> GetToken(string baseUrl)
        {
            string privateSecret = "78ceb13a-84fe-4d52-af77-0e8a6d22607d";

            DateTime now = DateTime.UtcNow;
            long unixTimestamp = (long)(now.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
            Console.WriteLine(unixTimestamp);
            int random = new Random().Next(1, 9999);
            Console.WriteLine(random);
            string originStr = privateSecret + unixTimestamp.ToString() + random;

            string originResult = ComputeSHA1(originStr);

            Dictionary<string, string> headers = new Dictionary<string, string>
            {
                { "Content-Type", "application/json" }
            };

            TokenRequest tokenRequest = new TokenRequest()
            {
                Random = random,
                Secret = originResult,
                Tenantid = "pda",
                Timestamp = unixTimestamp,
                User = "13456982386"
            };
            using var client = new HttpClient();
            // 将参数序列化为JSON格式的字符串
            string json = JsonConvert.SerializeObject(tokenRequest);

            // 构造请求内容
            var content = new StringContent(json, Encoding.UTF8, "application/json");

            // 发送POST请求
            HttpResponseMessage response = await client.PostAsync(baseUrl+"/railway/async/getToken", content);

            // 处理响应
            if (response.IsSuccessStatusCode)
            {
                var responseBody = await response.Content.ReadAsStringAsync();

                var responseObject = System.Text.Json.JsonSerializer.Deserialize<GETToken>(responseBody);

                return responseObject.data.token;
            }
            else
            {
                return "";
            }

        }

        private static string ComputeSHA1(string input)
        {
            using (SHA1Managed sha1 = new SHA1Managed())
            {
                byte[] inputBytes = Encoding.UTF8.GetBytes(input);
                byte[] hashBytes = sha1.ComputeHash(inputBytes);

                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < hashBytes.Length; i++)
                {
                    sb.Append(hashBytes[i].ToString("x2")); // Convert byte to hexadecimal string
                }
                return sb.ToString();
            }
        }

        public static string GetFullUrl(string path)
        {
            return $"{baseUrl}/{path}";
        }
    }




}
